package com.baozhun.mall.common.bindadapter

import android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
import android.os.SystemClock
import android.text.Editable
import android.text.Html
import android.text.InputType
import android.text.TextWatcher
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.CompoundButton
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.text.buildSpannedString
import androidx.core.text.inSpans
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.baozhun.mall.common.R
import com.baozhun.mall.common.util.Constants
import com.baozhun.mall.common.util.CornerTransform
import com.baozhun.mall.common.util.MoneyUtils
import com.baozhun.mall.common.util.UrlUtil
import com.blankj.utilcode.util.SizeUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.fondesa.recyclerviewdivider.dividerBuilder
import com.fondesa.recyclerviewdivider.staggeredDividerBuilder
import me.hgj.jetpackmvvm.ext.view.textString


/**
 * 作者　: hegaojian
 * 时间　: 2019/12/23
 * 描述　: 自定义 BindingAdapter
 */
object CustomBindAdapter {

    @BindingAdapter(value = ["checkChange"])
    @JvmStatic
    fun checkChange(checkbox: CheckBox, listener: CompoundButton.OnCheckedChangeListener) {
        checkbox.setOnCheckedChangeListener(listener)
    }

    @BindingAdapter(value = ["showPwd"])
    @JvmStatic
    fun showPwd(view: EditText, boolean: Boolean) {
        if (boolean) {
            view.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
        } else {
            view.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
        }
        view.setSelection(view.textString().length)
    }

    /**
     * 实现textView显示HTML标签
     */
    @BindingAdapter(value = ["htmlText", "textColor"], requireAll = false)
    @JvmStatic
    fun htmlText(view: TextView, htmlText: String?, textColor: String?) {
        if (htmlText?.isNotEmpty() == true) {
            view.text = Html.fromHtml(htmlText)
        }
        if (textColor?.isNotEmpty() == true) {
            view.setTextColor(Color.parseColor(textColor))
        }
    }

    /**
     * 内容中间加一条横线
     *
     * @param tv      当前操作的控件
     * @param addMiddleLineText 内容
     * @param addMoneySign  是否加金钱符号 中间
     */
    @BindingAdapter(
        value = ["text", "addMiddleLine", "addMoneySign", "addRedStar", "addUnderLineText"],
        requireAll = false
    )
    @JvmStatic
    fun addMiddleLine(
        tv: TextView,
        text: String?,
        addMiddleLineText: Boolean?,
        addMoneySign: Boolean?,
        addRedStar: Boolean?,
        addUnderLineText: Boolean?
    ) {
        //添加中劃線
        if (addMiddleLineText == true) {
            tv.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
            tv.paint.isAntiAlias = true
        }
        if (addUnderLineText == true) {
            tv.paint.flags = Paint.UNDERLINE_TEXT_FLAG
            tv.paint.isAntiAlias = true
        }
        var text = if (text.isNullOrEmpty()) tv.text else text
        //是否添加金額符號
        text =
            if (addMoneySign == true && !text.contains(Constants.Common.MONEY_TAG) && !text.contains(Constants.Common.MONEY_TAG2)) "¥$text" else text
        //是否添加星號前綴
        tv.text = buildSpannedString {
            if (addRedStar == true) inSpans(ForegroundColorSpan(tv.context.getColor(com.baozhun.mall.res.R.color.color_C0372F))) {
                append("*")
            }
            append(text)
        }
    }

    /**
     * 实现文字小数点后面大小可设置
     */
    @BindingAdapter(value = ["text", "pointSize", "prefixMoneySignSize", "amountFormat", "removeMoneySignSize"], requireAll = false)
    @JvmStatic
    fun text(view: TextView, text: String?, pointSize: Int, prefixMoneySignSize: Int?, amountFormat: Boolean, removeMoneySignSize: Boolean?) {
        var textTemp = text ?: ""
        if (amountFormat) {
            textTemp = MoneyUtils.convert(textTemp).toString()
        }
        var textList = textTemp?.split(".")?.toMutableList()
        //文字大小缺省处理
        var pointSizeTemp = if (pointSize == 0) view.textSize.toInt() else SizeUtils.dp2px(pointSize.toFloat())
        var moneySignSizeTemp =
            if (prefixMoneySignSize == null || prefixMoneySignSize == 0) view.textSize.toInt() else SizeUtils.dp2px(
                prefixMoneySignSize.toFloat()
            )
        //如果设置了金额符号的大小，则判断字符串前缀是否携带金额符号，有则去掉，后面再统一做添加处理
        if (prefixMoneySignSize != null && prefixMoneySignSize != 0 || removeMoneySignSize == true) {
            textTemp = textTemp.removePrefix(Constants.Common.MONEY_TAG).removePrefix(Constants.Common.MONEY_TAG2)
        }
        if (textList?.size == 2 && pointSize != 0) {
            view.text = buildSpannedString {
                if (prefixMoneySignSize != null && prefixMoneySignSize != 0) {
                    inSpans(AbsoluteSizeSpan(moneySignSizeTemp)) {
                        append(Constants.Common.MONEY_TAG)
                    }
                }
                append(textList?.get(0))
                inSpans(AbsoluteSizeSpan(pointSizeTemp)) {
                    append(".").append(textList?.get(1))
                }
            }
        } else {
            view.text = buildSpannedString {
                if (prefixMoneySignSize != null && prefixMoneySignSize != 0) {
                    inSpans(AbsoluteSizeSpan(moneySignSizeTemp)) {
                        append(Constants.Common.MONEY_TAG)
                    }
                }
                append(textTemp)
            }
        }
    }

    /**
     * xml支持是否选中
     */
    @BindingAdapter(value = ["selected"])
    @JvmStatic
    fun viewSelected(view: View, isSelected: Boolean?) {
        if (isSelected != null) {
            view.isSelected = isSelected
        }
    }

    /**
     * 设置view的宽度,高度,等属性
     *
     */
    @BindingAdapter(
        value = ["viewWidth", "viewHeight", "viewWeight", "id", "hint", "isBold", "editable"],
        requireAll = false
    )
    @JvmStatic
    fun layoutWidth(
        view: View,
        width: Int,
        height: Int,
        weight: Int?,
        id: Int,
        hint: String?,
        isBold: Boolean?,
        editable: Boolean
    ) {
        val layoutParams = view.layoutParams
        if (width != 0) layoutParams.width = width
        if (height != 0) layoutParams.height = height else layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
        if (id != 0) view.id = id
        if (layoutParams is LinearLayout.LayoutParams && weight != null) {
            layoutParams.weight = weight.toFloat()
        }
        if (view is EditText && hint != null) view.hint = hint
        if (view is TextView && isBold != null) view.typeface = Typeface.DEFAULT_BOLD
        if (view is EditText && editable != null) {
            view.isFocusable = editable
            view.isCursorVisible = editable
            view.isFocusableInTouchMode = editable
        }

    }

    /**
     * 设置view的各种间距
     *
     */
    @BindingAdapter(
        value = ["layout_marginLeft", "layout_marginTop", "layout_marginRight", "layout_marginBottom"],
        requireAll = false
    )
    @JvmStatic
    fun setViewAttribute(
        view: View, layoutMarginLeft: Float, layoutMarginTop: Float, layoutMarginRight: Float, layoutMarginBottom: Float
    ) {
        val layoutParams = view.layoutParams
        if (layoutParams is ViewGroup.MarginLayoutParams) {
            var tempLayoutMarginLeft =
                if (layoutMarginLeft == null || layoutMarginLeft == 0f) layoutParams.leftMargin else layoutMarginLeft
            var tempLayoutMarginTop =
                if (layoutMarginTop == null || layoutMarginTop == 0f) layoutParams.topMargin else layoutMarginTop
            var tempLayoutMarginRight =
                if (layoutMarginRight == null || layoutMarginRight == 0f) layoutParams.rightMargin else layoutMarginRight
            var tempLayoutMarginBottom =
                if (layoutMarginBottom == null || layoutMarginBottom == 0f) layoutParams.bottomMargin else layoutMarginBottom
            layoutParams.setMargins(
                tempLayoutMarginLeft.toInt(),
                tempLayoutMarginTop.toInt(),
                tempLayoutMarginRight.toInt(),
                tempLayoutMarginBottom.toInt()
            )
        }
    }

    /**
     * 设置view显示隐藏
     */
    @BindingAdapter(value = ["isVisible"])
    @JvmStatic
    fun setVisible(view: View, isVisible: Boolean) {
        view.visibility = if (isVisible) View.VISIBLE else View.GONE
    }

    @BindingAdapter(value = ["circleImageUrl"])
    @JvmStatic
    fun circleImageUrl(view: ImageView, url: String?) {
        if (url.isNullOrEmpty()) return
        Glide.with(view.context.applicationContext).load(url).apply(RequestOptions.bitmapTransform(CircleCrop()))
            .transition(DrawableTransitionOptions.withCrossFade(500)).into(view)
    }

    @BindingAdapter(
        value = ["imageUrl", "boundRadius", "topLeftRadius", "topRightRadius", "bottomLeftRadius", "bottomRightRadius"],
        requireAll = false
    )
    @JvmStatic
    fun loadImageUrl(
        view: ImageView,
        url: String?,
        boundRadius: Int? = null,
        topLeftRadius: Int? = null,
        topRightRadius: Int? = null,
        bottomLeftRadius: Int? = null,
        bottomRightRadius: Int? = null
    ) {
        if (url.isNullOrEmpty()) return
        var hasBoundRadius = boundRadius != null && boundRadius > 0
        var hasTopLeftRadius = topLeftRadius != null && topLeftRadius > 0
        var hasTopRightRadius = topRightRadius != null && topRightRadius > 0
        var hasBottomLeftRadius = bottomLeftRadius != null && bottomLeftRadius > 0
        var hasBottomRightRadius = bottomRightRadius != null && bottomRightRadius > 0
        if (hasBoundRadius || hasTopLeftRadius || hasTopRightRadius || hasBottomLeftRadius || hasBottomRightRadius
        ) {
            var radius = SizeUtils.dp2px(
                arrayListOf(
                    boundRadius,
                    topLeftRadius,
                    topRightRadius,
                    bottomLeftRadius,
                    bottomRightRadius
                ).find { it != null && it > 0 }!!.toFloat()
            ).toFloat()
            var cornerTransform = CornerTransform(view.context, radius)
            if (hasBoundRadius) {
                cornerTransform.setNeedCorner(leftTop = true, rightTop = true, leftBottom = true, rightBottom = true)
            } else {
                cornerTransform.setNeedCorner(hasTopLeftRadius, hasTopRightRadius, hasBottomLeftRadius, hasBottomRightRadius)
            }
            Glide.with(view.context.applicationContext).load(url)
//                .error(R.drawable.ic_default_pic)
//                .placeholder(R.drawable.ic_default_pic)
                .transform(cornerTransform)
                .transition(DrawableTransitionOptions.withCrossFade(500)).into(view)
        } else {

            if (UrlUtil.isGifUrl(url)) {
                Glide.with(view.context.applicationContext)
                    .asGif()
                    .load(url)
//                .error(R.drawable.ic_default_pic)
//                .placeholder(R.drawable.ic_default_pic)
                    .transition(DrawableTransitionOptions.withCrossFade(500)).into(view)
            } else {
                Glide.with(view.context.applicationContext)
                    .load(url)
//                .error(R.drawable.ic_default_pic)
//                .placeholder(R.drawable.ic_default_pic)
                    .dontAnimate()
                    .transition(DrawableTransitionOptions.withCrossFade(500)).into(view)
            }

        }
    }

    @BindingAdapter(value = ["imageResId", "boundRadius"], requireAll = false)
    @JvmStatic
    fun loadImageResId(view: ImageView, imageResId: Int?, boundRadius: Int? = null) {

        if (imageResId == null || imageResId == 0) return
        if (boundRadius != null && boundRadius > 0) {
            val roundedCorners = RoundedCorners(SizeUtils.dp2px(boundRadius.toFloat()))
            val multiTransformation = MultiTransformation(CenterCrop(), roundedCorners)
            Glide.with(view.context.applicationContext).load(imageResId)
                .error(com.baozhun.mall.res.R.drawable.ic_default_pic)
                .placeholder(com.baozhun.mall.res.R.drawable.ic_default_pic)
                .apply(RequestOptions.bitmapTransform(multiTransformation))
                .transition(DrawableTransitionOptions.withCrossFade(500)).into(view)
        } else {
            Glide.with(view.context.applicationContext).load(imageResId)
                .error(com.baozhun.mall.res.R.drawable.ic_default_pic)
                .placeholder(com.baozhun.mall.res.R.drawable.ic_default_pic)
                .dontAnimate()
                .transition(DrawableTransitionOptions.withCrossFade(500)).into(view)
        }
    }

    @BindingAdapter(value = ["afterTextChanged"])
    @JvmStatic
    fun EditText.afterTextChanged(action: (String) -> Unit) {
        addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                action(s.toString())
            }
        })
    }

    @BindingAdapter(value = ["noRepeatClick"])
    @JvmStatic
    fun setOnClick(view: View, clickListener: () -> Unit) {
        val mHits = LongArray(2)
        view.setOnClickListener {
            System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1)
            mHits[mHits.size - 1] = SystemClock.uptimeMillis()
            if (mHits[0] < SystemClock.uptimeMillis() - 500) {
                clickListener.invoke()
            }
        }
    }

    /**
     * 设置recycleView属性
     */
    @BindingAdapter(
        value = ["itemDecorationHeight", "itemDecorationInsetLeft", "itemDecorationInsetRight", "itemDecorationColorId"],
        requireAll = false
    )
    @JvmStatic
    fun setRecycleViewAttr(
        view: RecyclerView,
        itemDecorationHeight: Float,
        insetLeft: Int,
        insetRight: Int,
        colorId: Int = Color.TRANSPARENT
    ) {
        if (view.layoutManager is StaggeredGridLayoutManager) {
            view.addItemDecoration(
                view.context.staggeredDividerBuilder()
                    .size(SizeUtils.dp2px(itemDecorationHeight))
                    .color(colorId)
                    .build()
            )
        } else {
            view.addItemDecoration(
                view.context.dividerBuilder()
                    .size(SizeUtils.dp2px(itemDecorationHeight))
                    .color(colorId)
                    .insets(SizeUtils.dp2px(insetLeft.toFloat()), SizeUtils.dp2px(insetRight.toFloat()))
                    .build()
            )
        }

    }
}